<template>
    <div>
        <a-modal
         v-model:visible="visible" 
         :title="formState.id?(formState.view?'查看':'编辑'):'新增'"  
         @ok="handleOk" 
         @cancel="visible = false"
         class="enterpriseInformationManagement-add-edit-modal4"
         width="100%"
         wrapClassName="n-1-enterpriseInformationManagement-addEdit4-modal"
         :footer="null"
        >
            <div v-if="visible" style="padding-bottom: 50px;">
                <a-form :form="form" layout="horizontal" class="form-descriptions-content-box">
                    <a-descriptions :column="3" bordered >
                        <a-descriptions-item>
                            <span slot="label" class="descriptions-label-slot">
                                <span class="xhText">*</span>
                                供应商类别
                            </span>
                            <a-form-item class="zm-form-model">
                                <a-input
                                    v-model:value="formState.fgyslb" 
                                    placeholder="请输入供应商类别"
                                    v-decorator="[
                                        'fgyslb', { initialValue:formState.fgyslb, rules: rules.fgyslb}
                                    ]"
                                />
                            </a-form-item>
                        </a-descriptions-item>
                        <a-descriptions-item>
                            <span slot="label" class="descriptions-label-slot">
                                <span class="xhText">*</span>
                                供应商名称
                            </span>
                            <a-form-item class="zm-form-model">
                                <a-input
                                    v-model:value="formState.fscsmc" 
                                    placeholder="请输入供应商名称"
                                    v-decorator="[
                                        'fscsmc', { initialValue:formState.fscsmc, rules: rules.fscsmc}
                                    ]"
                                />
                            </a-form-item>
                        </a-descriptions-item>
                        <a-descriptions-item>
                            <span slot="label" class="descriptions-label-slot">
                                <span class="xhText">*</span>
                                供应商等级
                            </span>
                            <a-form-item class="zm-form-model">
                                <a-select
                                    ref="select"
                                    placeholder="请选择供应商等级"
                                    v-model:value="formState.fgysdj"
                                    v-decorator="[
                                        'fgysdj', { initialValue:formState.fgysdj, rules: rules.fgysdj}
                                    ]"
                                >
                                    <a-select-option value="一级">一级</a-select-option>
                                    <a-select-option value="二级">二级</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-descriptions-item>
                        <a-descriptions-item>
                            <span slot="label" class="descriptions-label-slot">
                                <span class="xhText">*</span>
                                审计有效期
                            </span>
                            <a-form-item class="zm-form-model">
                                <span v-if="formState.fwlyxq == '长期有效'">{{ formState.fwlyxq }}</span>
                                <a-date-picker
                                v-else
                                v-model:value="formState.fwlyxq"
                                placeholder="请选择库存有效期"
                                v-decorator="[
                                    'fwlyxq', { initialValue:formState.fwlyxq, rules: rules.fwlyxq}
                                ]"/>
                                <a-button style="margin-left: 5px;" v-if="formState.fwlyxq !== '长期有效'" class="blue-btn" type="primary" @click="formState.fwlyxq = '长期有效'"> 长期有效 </a-button>
                            </a-form-item>
                        </a-descriptions-item>
                        <a-descriptions-item>
                            <span slot="label" class="descriptions-label-slot">
                                <span class="xhText">*</span>
                                供应商地址
                            </span>
                            <a-form-item class="zm-form-model">
                                <a-textarea 
                                    placeholder="请输入供应商地址"
                                    style="width: 100%;"
                                    v-model:value="formState.fgysdz"
                                    :autosize="{ minRows: 2, maxRows: 10000 }"
                                    v-decorator="[
                                        'fgysdz', { initialValue:formState.fgysdz, rules: rules.fgysdz}
                                    ]"
                                ></a-textarea>
                            </a-form-item>
                        </a-descriptions-item>
                    </a-descriptions>
                </a-form>
                <div style="width: 100%;margin-bottom: 20px;">
                    <a-button class="blue-btn" type="primary" @click="addCatalog">选择物料</a-button>
                    <div v-if="existingDirectoryList.length">
                        <table border="1" class="existing-table">
                            <tr>
                                <th>物料编号</th>
                                <th>物料名称</th>
                                <th>物料等级</th>
                                <th>规格</th>
                                <th>操作</th>
                            </tr>
                            <tr v-for="(item,index) in existingDirectoryList" :key="index">
                                <td>{{ item.fwlbh }}</td>
                                <td>{{ item.fwlmc }}</td>
                                <td>{{ item.fwldj }}</td>
                                <td>{{ item.fgg }}</td>
                                <td>
                                    <a-button class="red-btn" type="primary" @click="deleteCatalog(item)">删除</a-button>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
                <div style="width: 100%;">
                    <table border="1" class="material-table">
                        <tr>
                            <th style="text-align: center;padding: 5px;">文件目录</th>
                            <th style="text-align: center;padding: 5px;">文件清单</th>
                            <th style="text-align: center;padding: 5px;">操作 <span style="color: red;font-size: 12px;">（提示：批量上传文件放在同一个文件夹内，选择文件夹上传）</span></th>
                        </tr>
                        <tr v-for="(item,index) in fjxxList" :key="index">
                            <td style="width: 30%;text-align: center;">{{ item.wjml }}</td>
                            <td style="width: 50%;">
                                <div style="display: flex;width: 100%;flex-wrap: wrap;">
                                    <div class="file-td-box" v-for="(term,tIndex) in item.wjList">
                                        <a-icon class="delete-icon-v" type="delete" @click="deleteClick(term)" v-if="!formState.view"/>
                                        <a-icon class="eye-icon-v" type="eye" @click="viewClick(term)" v-if="term.fwjlx == '.pdf'"/>
                                        <a-icon class="download-icon-v" type="download" @click="downloadClick(term)"/>
                                        <a-icon class="file-icon-v" type="file-pdf" />
                                        <span>{{ term.fwjxsmc+term.fwjlx }}</span>
                                    </div>
                                </div>
                            </td>
                            <td style="width: 20%;">
                                <div style="display: flex;justify-content: center;padding: 5px;" v-if="!formState.view">
                                    <a-upload 
                                    :disabled="uploadLoading"
                                    style="display: inline-block;" 
                                    :beforeUpload="enterpriseBeforeUpload" 
                                    action="" 
                                    @change="enterpriseUpload($event,item)">
                                        <a-button :loading="uploadLoading" style="margin-right: 15px;" class="blue-btn" type="primary" @click="uploadSave">上传</a-button>
                                    </a-upload>
                                    <!-- <a-button v-else style="margin-right: 15px;" class="blue-btn" type="primary" @click="handleOk(true)">上传</a-button> -->
                                    <a-upload 
                                    :disabled="uploadLoading"
                                    style="display: inline-block;" 
                                    :beforeUpload="enterpriseBeforeUpload" 
                                    action="" 
                                    @change="enterpriseUpload($event,item)" directory>
                                        <a-button :loading="uploadLoading" class="blue-btn" type="primary" @click="uploadSave">批量上传</a-button>
                                    </a-upload>
                                    <!-- <a-button v-else class="blue-btn" type="primary" @click="handleOk(true)">批量上传</a-button> -->
                                </div>
                                
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
            <div style="
                display: flex; justify-content: flex-end;
                margin-top: 20px; width: 100%;
                position: fixed; left: 0;
                bottom: 0; padding: 18px 24px;
                background-color: #fff;">
                <a-button @click="visible = false">取消</a-button>
                <a-button v-if="!formState.view" style="margin: 0 20px;" class="blue-btn" type="primary" @click="handleOk(true)">保存</a-button>
                <a-button v-if="!formState.view" class="blue-btn" type="primary" @click="handleOk(false)">保存并关闭</a-button>
            </div>
            <serverEditingView ref="serverEditingViewRef" @refreshChange="$event=>{}"/>
            <a-modal
            title="选择物料"
            :visible="catalogVisible"
            @ok="catalogHandleOk"
            @cancel="getExistingDate();catalogVisible = false"
            :width="800"
            >
                <div>
                    <table border="1" class="existing-table">
                        <tr>
                            <th></th>
                            <th>物料编号</th>
                            <th>物料名称</th>
                            <th>规格</th>
                        </tr>
                        <tr v-for="(item,index) in materialClassList" :key="index">
                            <td>
                                <a-checkbox v-if="item.isSelect" :checked="true" @change="catalogOnChange(item,index)"></a-checkbox>
                                <a-checkbox v-else :checked="false" @change="catalogOnChange(item,index)"></a-checkbox>
                            </td>
                            <td>{{ item.fwlbh }}</td>
                            <td>{{ item.fwlmc }}</td>
                            <td>{{ item.fgg }}</td>
                        </tr>
                    </table>
                </div>
            </a-modal>
        </a-modal>
    </div>
</template>
<script>
import compSelector from '@/components/compSelector/compSelector.vue'
import serverEditingView from '@/components/comp-model-series/server-editing-view'
import moment from 'moment'
import YchConstant from "@/api/YchConstant";
import blobType from '@/common/blobType'
import { 
    spcyQyInfoQueryYlgyssjWjml, 
    spcyQyInfoUploadMoreTypeFile, 
    getFileTypeServe, 
    deleteFileById, 
    getCrossLocalFile, 
    spcyQyInfoqueryAllWlmlList,
    spcyQyInfoqueryWlgyssjBySjIdList,
    spcyQyInfoaddWlgyssjGx,
    spcyQyInfodeleteWlgyssjGx,
} from './service/index'
export default {
    components:{
        serverEditingView,
        compSelector,
    },
    props:{

    },
    data(){
        return{
            catalogVisible:false,
            visible:false,
            formState:{},
            form: this.$form.createForm(this, { name: 'coordinated' }),
            rules:{
                fzlbz: [{
                    required: true,
                    message: '请输入质量标准',
                    trigger: 'blur',
                }],
                fgyslb: [{
                    required: true,
                    message: '请输入供应商类别',
                    trigger: 'blur',
                }],
                fscsmc: [{
                    required: true,
                    message: '请输入生产商名称',
                    trigger: 'blur',
                }],
                fscsdz: [{
                    required: true,
                    message: '请输入生产商地址',
                    trigger: 'blur',
                }],
                fgysdj: [{
                    required: true,
                    message: '请选择供应商等级',
                    trigger: 'blur',
                }],
                fgysdz: [{
                    required: true,
                    message: '请输入供应商地址',
                    trigger: 'blur',
                }],
                fwlyxq: [{
                    type:'object',
                    required: true,
                    message: '请选择审计有效期',
                    trigger: 'blur',
                }],
            },
            fjxxList:[],
            uploadLoading:false,
            materialClassList:[],
            selectMaterialClassId:[],
            existingDirectoryList:[],
            existingDirectoryKey:null,
        }
    },
    watch:{

    },
    mounted(){
    },
    methods:{
        getData(val){
            if(val.isAddCatalog){
                this.catalogVisible = true
                this.getExistingDate()
            }
            this.formState = {}
            this.formState = {...val,isAddCatalog:false}
            this.formState.fwlyxq = val.fwlyxq?(val.fwlyxq == '长期有效'?val.fwlyxq:moment(val.fwlyxq)):''
            this.getFile(val)
            //查询物料分类
            spcyQyInfoqueryAllWlmlList({fqyid:this.formState.fqyid}).then(res=>{
                if(res.code == 200){
                    //console.log('物料分类',res)
                    this.materialClassList = res.result
                    this.getExistingDate()
                }else{
                    this.$message.warning(res.message)
                }
            })
            
        },
        getExistingDate(){
            this.selectMaterialClassId = []
            spcyQyInfoqueryWlgyssjBySjIdList({fwlsjid:this.formState.id}).then(res=>{
                if(res.code == 200){
                    this.existingDirectoryList = res.result
                    this.existingDirectoryKey = Date.now()
                    res.result.forEach((item,index)=>{
                        this.selectMaterialClassId.push(item.id)
                    })
                    this.materialClassList = this.materialClassList.map(i=>{return{...i,isSelect:this.selectMaterialClassId.indexOf(i.id) == -1?false:true}})
                    //console.log('更改后的',this.materialClassList)
                }else{
                    this.$message.warning(res.message)
                }
            })
        },
        getFile(val){
            spcyQyInfoQueryYlgyssjWjml({id:val.id?val.id:''}).then(res=>{
                if(res.code == 200){
                    this.fjxxList = res.result
                }else{
                    this.$message.warning(res.message)
                }
            })
        },
        deleteClick(val){
            var that = this
            this.$confirm({
                title:'您确认要删除吗？',
                // icon: createVNode(ExclamationCircleOutlined),
                onOk() {
                    deleteFileById({id:val.id}).then(res=>{
                        if(res.code == 200){
                            that.$message.success('删除成功')
                            that.getFile(that.formState)
                        }else{
                            that.$message.warning(res.message)
                        }
                    })
                },
                
            });
        },
        viewClick(val){
            this.$refs.serverEditingViewRef.getData({id:val.id,fwjlx:val.fwjlx,type:'企业信息'})
            this.$refs.serverEditingViewRef.serverEditingVisible = true
        },
        lookOverClick(val){
            getFileTypeServe({id:val.id}).then(res=>{
                if(res.code == 200){
                    if(res.result == '.pdf'){
                        window.open(
                            bootConfig[process.env.NODE_ENV].locality_ApI+YchConstant.SPZX_SPCY+'/spcySqsxWjjl/getCrossLocalFile?id='+val.id
                        )
                    }else{
                        this.$message.warning('只能查看pdf文件')
                    }
                    
                }
                
            })
        },
        downloadClick(val){
            
            var that = this
            var fileName = val.fwjxsmc
            let param = {id:val.id}
            getFileTypeServe({id:val.id}).then(res=>{
                if(res.code == 200){
                    getCrossLocalFile(param).then((data) => {
                        if (!data) {
                            that.$message.warning('文件下载失败')
                            return
                        }else{
                        // if (typeof window.navigator.msSaveBlob !== 'undefined') {
                        //     window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }))
                        // } else {
                            let url = window.URL.createObjectURL(new Blob([data], { type: blobType.type[blobType.suffix.indexOf(val.fwjlx)] }))
                            let link = document.createElement('a')
                            link.style.display = 'none'
                            link.href = url
                            link.setAttribute('download', fileName + res.result)
                            document.body.appendChild(link)
                            link.click()
                            document.body.removeChild(link) //下载完成移除元素
                            window.URL.revokeObjectURL(url) //释放掉blob对象
                        // }
                        }
                    })
                }
                
            })
        },
        enterpriseBeforeUpload(e){
            return false
        },
        uploadSave(){
            if(!this.formState.id){
                this.handleOk(true,true)
            }
        },
        enterpriseUpload({file},val){//
            var that = this
            this.uploadLoading = true
            if(typeof file.uid !== 'undefined') {
                // if(file.name.indexOf(".xls") !== -1 || file.name.indexOf(".xlsx") !==-1) {
                    const fileData = new FormData();
                    fileData.append("file",file);
                    fileData.append("id",this.formState.id);
                    fileData.append("fwjlx1",val.wjml);
                    
                    spcyQyInfoUploadMoreTypeFile(fileData).then(res => {
                        if(res.code){
                            if(res.code == 200){
                                this.uploadLoading = false
                                that.$message.success(res.message)
                            }else{
                                this.uploadLoading = false
                                that.$message.warning(res.message)
                            }
                            
                        }
                        if(res.byteLength){
                            if(res.code && res.code !== 200){
                                this.uploadLoading = false
                                that.$message.warning('请上传对应文件类型或者联系管理员!')
                            }else{
                                this.uploadLoading = false
                                that.$message.success('上传成功')
                            }
                        }
                        this.getFile(this.formState)
                    })
                // }
                
            }
        },
        addCatalog(){
            this.form.validateFields((err, values) => {
                
                if(!this.formState.id){
                    this.handleOk(true)
                }
                this.catalogVisible = true
            })
        },
        //删除物料
        deleteCatalog(val){
            var that = this
            this.$confirm({
                title:'您确认要删除吗？',
                onOk() {
                    spcyQyInfodeleteWlgyssjGx({id:val.id}).then(res=>{
                        if(res.code == 200){
                            that.getExistingDate()
                            that.$message.success(res.message)
                        }else{
                            that.$message.warning(res.message)
                        }
                    })
                }
            })
        },

        catalogOnChange(val,index){
            if(this.selectMaterialClassId.indexOf(val.id) !== -1){
                this.selectMaterialClassId.splice(this.selectMaterialClassId.indexOf(val.id),1)
            }else{
                this.selectMaterialClassId.push(val.id)
            }
            this.materialClassList[index].isSelect = !val.isSelect
        },
        catalogHandleOk(){
            if(this.selectMaterialClassId.length){
                spcyQyInfoaddWlgyssjGx({fwlmlid:this.selectMaterialClassId.join(','),fwlsjid:this.formState.id}).then(res=>{
                    if(res.code == 200){
                        this.getExistingDate()
                        this.catalogVisible = false
                    }else{
                        this.$message.warning(res.message)
                    }
                })
            }else{
                this.$message.warning('请先选择物料')
            }
        },
        handleOk(val){

            this.form.validateFields((err, values) => {
                if (!err) {
                    if(this.formState.id){
                        this.$emit('editItem',{
                            ...this.formState,...values,
                            fwlyxq:this.formState.fwlyxq?(this.formState.fwlyxq == '长期有效'?this.formState.fwlyxq:moment(this.formState.fwlyxq).format('YYYY-MM-DD')):''
                        },val)
                    }else{
                        this.$emit('addItem',{
                            ...this.formState,...values,
                            fwlyxq:this.formState.fwlyxq?(this.formState.fwlyxq == '长期有效'?this.formState.fwlyxq:moment(this.formState.fwlyxq).format('YYYY-MM-DD')):''
                        },val)
                    }
                    
                }
            })
        },
    }
}
</script>
<style lang="less">
.enterpriseInformationManagement-add-edit-modal4{
    .add-edit-form{
        display: flex;
        flex-wrap: wrap;
        .ant-form-item{
            display: flex;
            margin-bottom: 5px;
        }
        .ant-form-item-label{
            width: 130px;
        }
        .ant-form-item-control-wrapper{
            width: 100%;
        }
        .flex-1-box{
            width: 100%;
            .ant-form-item-control-wrapper{
                flex: 1;
            }
        }
    }
    .material-table{
        width: 100%;
        border-color: #d9d9d9 !important;
    }
}
.file-td-box{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-content: space-between;
    width: 104px;
    height: 104px;
    overflow: hidden;
    border-radius: 2px;
    border: 1px solid #d9d9d9;
    padding: 8px;
    margin: 8px;
    position: relative;
    .delete-icon-v{
        font-size: 16px;
        position: absolute;
        color: rgb(24, 144, 255);
        right: 11px;
        top: 3px;
    }
    .eye-icon-v{
        font-size: 16px;
        position: absolute;
        color: rgb(24, 144, 255);
        right: 11px;
        top: 38px;
    }
    .download-icon-v{
        width: 20px;
        font-size: 16px;
        position: absolute;
        color: rgb(24, 144, 255);
        right: 9px;
        top: 20px;
    }
    .download-icon-apply{
        top: 10px;
    }
    .fjbz-text-v{
        color: #ff8000;
        font-size: 12px !important;
        display: inline-block;
        width: 28px;
        position: absolute;
        top: 5px;
        left: 3px;
    }
    .file-icon-v{
        font-size: 42px;
        color: rgb(24, 144, 255);
    }
    .file-icon-v{
        font-size: 42px;
        color: rgb(24, 144, 255);
    }
    span{
        height: 40px;
        display:block;
        text-overflow: -o-ellipsis-lastline;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        line-clamp: 2;
        -webkit-box-orient: vertical;
        font-size: 14px;
    }
}
.n-1-enterpriseInformationManagement-addEdit4-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }
  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: 100vh;
  }
  .ant-modal-body {
    flex: 1;
    height: calc(100vh);
    overflow-y: auto;
  }
}
.ant-upload-list{
    display: none;
}
.ant-upload-list-item{
    display: none !important;
}
.existing-table{
    width: 100%;
    border-color: #d9d9d9 !important;
    th,td{
        padding: 5px 10px;
    }
}
</style>